package com.Action;

import com.Dao.UserDao;
import com.Services.UserService;
import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.ServletActionContext;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by Administrator on 2017/3/15.
 */
public class LoginAction extends ActionSupport {
    private String userName;
    private String password;

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    /**
     * 用户登录动作
     * @return
     * @throws Exception
     */
    @Override
    public String execute() throws Exception {
        HttpServletRequest request= ServletActionContext.getRequest();
        request.setCharacterEncoding("utf-8");
        ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService us=ac.getBean(UserService.class);
        String result=us.login(userName,password);
        if(result.equals("error")){
            request.setAttribute("message","用户名或密码错误！");
        }else{
            //将用户信息存入会话
            if(request.getAttribute("message")!=null)
                request.removeAttribute("message");
            request.getSession().setAttribute("Account",userName);
            if(result.equals("admin")){
                request.getSession().setAttribute("privilege",9);
            }else {
                request.getSession().setAttribute("privilege",1);
            }
        }
        return result;
    }
}
